function tabButtonClick(elem) {
    $(elem).parent().find(".layui-btn").removeClass("layui-this").removeClass("layui-btn-normal").addClass("layui-btn-primary").css("color","#01AAED");
    $(elem).addClass("layui-this").addClass("layui-btn-normal").css("color","#fff");
    $("."+$(elem).attr("view-class")).css("display","none");
    $("#"+$(elem).attr("view-id")).css("display","block");
}


function genParam(json) {
    let param = "?";
    for (let key in json) {
        param += key+"="+json[key]+"&"
    }
    param = param.substring(0,param.length-1);

    return param;
}



// 模拟表单提交同步方式下载文件
// 能够弹出保存文件对话框
function downloadFileByForm(url) {
    console.log(url);
    let form = $("<form></form>").attr("action", url).attr("method", "post");
    form.appendTo('body').submit().remove();
}

function initOperator() {
    let index;
    $(".table-operator").mouseenter(function () {
        index = layer.tips($(this).attr("tip"),this);
    }).mouseleave(function () { //鼠标指针从 a标签 上离开时 发生mouseout 事件
        layer.close(index);
    })
}

/**
 * 解决当手机页面时，操作列的按钮失效问题。
 * 失效原因是操作列的宽度较小，点击时会悬浮一个窗口，里面的按钮失效
 */
function fixTableOperatorButton() {

    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

        // 缓存当前操作的是哪个表格的哪个tr的哪个td
        $(document).off('mousedown','.layui-table-grid-down')
            .on('mousedown','.layui-table-grid-down',function(event){
                table._tableTrCurr = $(this).closest('td');
            });

        $(document).off('click','.layui-table-tips-main [lay-event]')
            .on('click','.layui-table-tips-main [lay-event]',function(event){
                var elem = $(this);
                var tableTrCurr = table._tableTrCurr;
                if(!tableTrCurr){
                    return;
                }
                var layerIndex = elem.closest('.layui-table-tips').attr('times');
                // 关闭当前这个显示更多的tip
                layer.close(layerIndex);
                table._tableTrCurr.find('[lay-event="' + elem.attr('lay-event') + '"]').first().click();
            });
    });
}

/**
 * 通过表格操作列打开一个页面，此时打开的是一个弹出层
 * @param title
 * @param url
 */
function openTab(title, url) {
    layui.use(['miniTab'], function () {
        let  miniTab = layui.miniTab;
        // 打开新的窗口
        miniTab.openNewTabByIframe({
            href:url,
            title:title,
        });
    });
}


/**
 * 关闭自身
 */
function closeSubIframe() {
    layui.use(['miniTab'], function () {
        let  miniTab = layui.miniTab;
        miniTab.deleteCurrentByIframe();
    });
}

function refreshMainIframe(tabId) {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+tabId+"']")[0];
    if (iFrame != null && iFrame != undefined) {
        iFrame.contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+tabId+"']")[0];
    if (iFrame != null && iFrame != undefined) {
        iFrame.contentWindow.location.reload();
    }
}

function refreshBudgetIn() {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+_baseUrl+"budget/budget.action']")[0];

    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#budgetIn")[0].contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+_baseUrl+"budget/budget.action']")[0];
    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#budgetIn")[0].contentWindow.location.reload();
    }
}

function refreshBudgetOut() {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+_baseUrl+"budget/budget.action']")[0];

    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#budgetOut")[0].contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+_baseUrl+"budget/budget.action']")[0];
    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#budgetOut")[0].contentWindow.location.reload();
    }
}

function refreshHouseWaitIn() {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+_baseUrl+"house/houseInMain.action']")[0];

    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseWaitIn")[0].contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+_baseUrl+"house/houseInMain.action']")[0];
    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseWaitIn")[0].contentWindow.location.reload();
    }
}

function refreshHouseIn() {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+_baseUrl+"house/houseInMain.action']")[0];

    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseIn")[0].contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+_baseUrl+"house/houseInMain.action']")[0];
    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseIn")[0].contentWindow.location.reload();
    }
}

function refreshHouseWaitOut() {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+_baseUrl+"house/houseOutMain.action']")[0];

    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseWaitOut")[0].contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+_baseUrl+"house/houseOutMain.action']")[0];
    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseWaitOut")[0].contentWindow.location.reload();
    }
}
function refreshHouseOut() {
    let iFrame = $(window.parent.parent.document).find("iframe[src='"+_baseUrl+"house/houseOutMain.action']")[0];

    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseOut")[0].contentWindow.location.reload();
    }


    iFrame = $(window.parent.document).find("iframe[src='"+_baseUrl+"house/houseOutMain.action']")[0];
    if (iFrame != null && iFrame != undefined && iFrame.length != 0) {
        $(iFrame.contentDocument).find("#houseOut")[0].contentWindow.location.reload();
    }
}

function prompt1(title,value,tip, done) {
    layer.prompt({
        formType: 0,
        title: title,
        value: value
    }, function(value, index, elem){
        done(index, value);
    });
    //直接在弹出层代码后，编写js 改变弹出层的样式、属性、增加对象等。
    $(".layui-layer-content .layui-layer-input").attr("placeholder",tip);
}

function prompt_textarea(title, done) {
    layer.prompt({
        formType: 2,
        title: title,
    }, function(value, index, elem){
        done(index, $(".textarea").val());
    });
    //直接在弹出层代码后，编写js 改变弹出层的样式、属性、增加对象等。
    $(".layui-layer-content textarea.layui-layer-input").val("1").hide();
    $(".layui-layer-content").prepend("<textarea class='textarea' style='width: 300px;height: 100px;' type='text' autocomplete='off' class='layui-textarea'/>");
}

function prompt2(title,tip1,tip2, done) {
    layer.prompt({
        formType: 2,
        title: title,
    }, function(value, index, elem){
        done(index, $("#prompt2-input").val(), value);
    });
    //直接在弹出层代码后，编写js 改变弹出层的样式、属性、增加对象等。
    $(".layui-layer-content textarea.layui-layer-input").attr("placeholder",tip2);
    $(".layui-layer-content").prepend("<input type='text' style='margin-bottom:4px;' id='prompt2-input' placeholder='"+tip1+"' autocomplete='off' class='layui-input'/>");
}

function prompt2_val(title, value,tip, value2,tip2, done) {
    layer.prompt({
        formType: 2,
        value:value2,
        title: title,
    }, function(value, index, elem){
        done(index, $("#prompt2-input").val(), value);
    });
    //直接在弹出层代码后，编写js 改变弹出层的样式、属性、增加对象等。
    $(".layui-layer-content textarea.layui-layer-input").attr("placeholder",tip2);
    $(".layui-layer-content").prepend("<input type='text' style='margin-bottom:4px;' id='prompt2-input' value='"+value+"' placeholder='"+tip+"' autocomplete='off' class='layui-input'/>");
}

function get(url,process) {
    return $.ajax({
        url: url,
        type: 'GET',
        data: null,
        cache:false,
        dataType: "json",
        beforeSend: function () {
        },
        success: function (data) {
            if (process != null){
                process(data);
            }
        }
    });
}

function post(url,data, process) {
    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        cache:false,
        dataType: "json",
        contentType:"application/json",
        beforeSend: function () {
        },
        success: function (data) {
            if (process != null){
                process(data);
            }
        }
    });
}

function openBigDialogByTagId(title, content) {
    let area = [(document.documentElement.clientWidth-100)+'px', (document.documentElement.clientHeight-20)+'px'];
    let index = layer.open({
        title:title,
        skin: 'layui-layer-molv',
        area:  area,
        type: 1,
        content: content
    });
    return index;
}

function openMiddleDialogByTagId(title, content) {

    let area;
    if (document.documentElement.clientWidth < 460){
        area = [400+'px', 600+'px'];
    } else {
        area = [600+'px', 400+'px'];
    }

    let index = layer.open({
        title:title,
        skin: 'layui-layer-molv',
        area:  area,
        type: 1,
        content: content
    });
    return index;
}

function openLoadingDialog(content) {
    return layer.open({
        type: 1
        ,title: false //不显示标题栏
        ,closeBtn: false
        ,area: '300px;'
        ,shade: 0.8
        ,id: 'loading' //设定一个id，防止重复弹出
        ,moveType: 1 //拖拽模式，0或者1
        ,content: content
    });
}

function openBigHtmlDialog(title, url, process) {
    let area;
    if (document.documentElement.clientWidth<600){
        area = [(document.documentElement.clientWidth-8)+'px', (document.documentElement.clientHeight-8)+'px'];
    }else {
        area = [(document.documentElement.clientWidth-80)+'px', (document.documentElement.clientHeight-80)+'px'];
    }

    layer.open({
        title:title,
        area: area,
        skin: 'layui-layer-molv',
        type: 2,
        content: url,
        success: function(layero, index){
            if (process != undefined){
                process(layero, index);
            }
        }
    });
}

function openHtmlDialog(title, url, process) {
    let area;
    if (document.documentElement.clientWidth > 600){
        area = ['550px', (document.documentElement.clientHeight-40)+'px'];
    } else {
        area = [(document.documentElement.clientWidth-8)+'px', (document.documentElement.clientHeight-8)+'px'];
    }
    let index = layer.open({
        title:title,
        area: area,
        skin: 'layui-layer-molv',
        type: 2,
        content: url,
        success: function(layero, index){
            if (process != undefined){
                process(layero, index);
            }
        }
    });
    return index;
}

/**
 * name layui合并tbody中单元格的方法
 * @param fieldName  要合并列的field属性值
 * @param index 表格的索引值 从1开始
 * @desc 此方式适用于没有列冻结的单元格合并
 */
function alarmTableRowSpan(fieldName, index) {
    let fixedNode = document.getElementsByClassName("layui-table-body")[index - 1];
    if (!fixedNode) {
        return false;
    }
    let child = fixedNode.getElementsByTagName("td");
    let childFilterArr = [];
    // 获取data-field属性为fieldName的td
    for (let i = 0; i < child.length; i++) {
        if (child[i].getAttribute("data-field") == fieldName) {
            childFilterArr.push(child[i]);
        }
    }
    // 获取td的个数和种类
    let childFilterTextObj = {};
    for (let i = 0; i < childFilterArr.length; i++) {
        let childText = childFilterArr[i].textContent;
        if (childFilterTextObj[childText] == undefined) {
            childFilterTextObj[childText] = 1;
        } else {
            let num = childFilterTextObj[childText];
            childFilterTextObj[childText] = num * 1 + 1;
        }
    }
    // 给获取到的td设置合并单元格属性
    for (let key in childFilterTextObj) {
        let tdNum = childFilterTextObj[key];
        let canRowSpan = true;
        for (let i = 0; i < childFilterArr.length; i++) {
            if (childFilterArr[i].textContent == key) {
                if (canRowSpan) {
                    childFilterArr[i].setAttribute("rowspan", tdNum);
                    canRowSpan = false;
                } else {
                    childFilterArr[i].style.display = "none";
                }
            }
        }
    }
}

function ajaxSelect(url, selectName, head, process) {
    return get(url,function (res) {
        if (res.code == 1) {

            let $select = $("[name='"+selectName+"']");
            $select.empty();
            if (head != undefined && head != null && head.length > 0){
                $select.append("<option value=''>"+head+"</option>");
            }
            $.each(res.data,function (i,data) {
                $select.append("<option value='"+data.id+"'>"+data.name+"</option>");
            });
            formRender();

            if (process!= null && process != undefined) {
                process(res.data);
            }
        }
    });
}

function ajaxSelects(url, params) {
    return get(url,function (res) {
        if (res.code == 1) {
            for (var i=0;i<params.length;i++){
                let $select = $("[name='"+params[i].selectName+"']");
                let head = params[i].head;
                $select.empty();
                if (head != undefined && head != null && head.length > 0){
                    $select.append("<option value=''>"+head+"</option>");
                }
                $.each(res.data,function (i,data) {
                    $select.append("<option value='"+data.id+"'>"+data.name+"</option>");
                });
            }
            formRender();
        }
    });
}

function getByType(baseUrl, type, $no,showTip) {
    get(baseUrl + "sett/orderRule/getByType?type="+type, function (res) {
        if (res.code == 1){
            let current = parseInt(res.data.current);
            let num = parseInt(res.data.num);
            let max = "";
            for (let i=0;i<num;i++) {
                max += "9";
            }

            console.log("current:" + current + ",num:"+num + ",max:"+max);
            let no;
            if (current < parseInt(max)) {
                no = res.data.prefix + getYYYYMMDD() + preFillZero(current, num);
            } else {
                no = res.data.prefix + getYYYYMMDD() + current;
            }
            $no.val(no);
            $no.html(no);


            console.log($no.val());
            if (showTip){
                tip("编号加载成功");
            }
        } else {
            tip(res.msg);
        }
    });
}

function genTableIndex(condition, msg, d) {
    if (condition) {
        return "<span class='layui-badge layui-bg-gray'>"+msg+"</span>";
    } else {
        return d.LAY_INDEX;
    }
}

function genTableIndexGreen(condition, msg, d) {
    if (condition) {
        return "<span class='layui-badge layui-bg-green'>"+msg+"</span>";
    } else {
        return d.LAY_INDEX;
    }
}

function setTableLineCss(lay_id, data, field,value, clazz) {
    $.each(data,function (index,item) {
        //逻辑判断
        if(item[field] == value){
            //改变TR标签内字体颜色
            $('[lay-id="'+lay_id+'"]').find('tbody tr[data-index="'+ index +'"]').addClass(clazz);
        }
    });
}

function setTotalRow(dataField, value, clazz) {
    let $cell = $(".layui-table-total").find("[data-field='"+dataField+"']").find(".layui-table-cell");
    if (!$cell.hasClass("layui-table-cell")){
        return;
    }
    if (clazz != undefined){
        $cell.addClass(clazz);
    }else {
        $cell.addClass("totalRowFont");
    }
    $cell.empty();
    $cell.append(value);
}

function setTotalRowWithParent($parent,dataField, value, clazz) {
    let $cell = $parent.find(".layui-table-total").find("[data-field='"+dataField+"']").find(".layui-table-cell");
    if (!$cell.hasClass("layui-table-cell")){
        return;
    }
    if (clazz != undefined){
        $cell.addClass(clazz);
    }else {
        $cell.addClass("totalRowFont");
    }
    $cell.empty();
    $cell.append(value);
}

function setTotalRowWithCenter(dataField, value, clazz) {
    let $cell = $(".layui-table-total").find("[data-field='"+dataField+"']").find(".layui-table-cell");
    if (!$cell.hasClass("layui-table-cell")){
        return;
    }
    $cell.css("text-align","center");
    if (clazz != undefined){
        $cell.addClass(clazz);
    }else {
        $cell.addClass("totalRowFont");
    }
    $cell.empty();
    $cell.append(value);
}


/**
 * 是否是合计行
 */
function notTotalRow(d) {
    if (d.id == undefined){
        return false;
    } else {
        return true;
    }
}

/**
 * 检查表格选中的数据，长度是0表示没有选择，返回false
 * @param data
 * @param tip
 * @returns {boolean}
 */
function checkSelectNum(data, msg) {
    if (data.length == 0){
        if (msg == undefined){
            tip("您未选择任何数据");
        } else {
            tip(msg);
        }
        return false;
    }
    return true;
}

/**
 * 是否有满足条件的数据
 * @param data
 * @param checkJson
 * @returns {boolean}
 */
function hasSelect(data, checkJsonArr) {
    if (checkJsonArr == undefined || checkJsonArr==null || checkJsonArr.length == 0){
        return false;
    }

    let flag = false;
    $.each(data, function (i,d) {
        //条件判断
        for(var j=0;j<checkJsonArr.length;j++){
            let json = checkJsonArr[j];
            console.log(json.key+"    "+json.value);
            console.log(d[json.key]);
            if (d[json.key] == json.value){
                tip("选择的数据中有已"+json.tip+"的，请重新选择");
                flag = true;
                break;
            }
        }

        if (flag){
            return false;
        }
    });

    return flag;
}

/**
 * 获取id
 * @param data
 * @returns {[]}
 */
function genIds(data) {
    let ids=[];
    $.each(data, function (i,d) {
        ids.push({id:d.id});
    });
    return ids;
}

/**
 * 获取id
 * @param data
 * @returns {[]}
 */
function genIdList(data) {
    let ids=[];
    $.each(data, function (i,d) {
        ids.push(d.id);
    });
    return ids;
}

function getPrice(price) {
    //不是字符串类型变成字符串类型
    if (typeof price != 'string'){
        price = price + "";
    }

    if (!isNumber(price)){
        price = "0";
    }
    return getFloat(price,_businessSet.pricePoint);
}

function getNumber(number) {
    //不是字符串类型变成字符串类型
    if (typeof number != 'string'){
        number = number + "";
    }

    if (!isNumber(number)){
        number = "0";
    }
    if (isInteger(number)) {
        return parseInt(number);
    }

    return getFloat(number,_businessSet.numPoint);
}


function getGoodsSnFromList(list,sn){
    if (emptyList(list)) {
        return;
    }

    for (let i=0;i<list.length;i++) {
        if (list[i].sn == sn) {
            return list[i];
        }
    }

    return null;
}

function genGoodsSnMap(list) {
    if (emptyList(list)) {
        return {};
    }
    let goodsSn_map = {};
    $.each(list, function (i,item) {
        if (!emptyEntity(item.goodsId) && item.sn) {
            if (goodsSn_map[item.goodsId] == undefined){
                goodsSn_map[item.goodsId] = [];
            }

            $.each(item.goodsSnList, function (i,d) {
                goodsSn_map[item.goodsId].push(d);
            });
        }
    });

    return goodsSn_map;
}

function genUploadTableList(list) {
    if (emptyList(list)) {
        return [];
    }
    $.each(list, function (i,item) {
        delete item.LAY_TABLE_INDEX;
    });

    return list;
}